package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前端规定后续请求都将JWT，放置于HTTP请求的Header中，其Header的key为`access_token`
        String token = request.getHeader("access_token");
        if(StringUtils.hasText(token)){
            //如果有值，则代表携带了token,获取当前的用户id和用户名，再放行
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("user_id", Long.class);
            String username = claims.get("username", String.class);
            //将用户id和用户名封装到在common中创建的对象中
            LoginUser loginUser = new LoginUser(userId,username);
            //然后将该对象放入ThreadLocal中，ThreadLocal的本质是一个Map集合，其中的键是当前的线程名，值可以是任意数据类型
            LoginUserContext.setLoginUser(loginUser);
            return true;
        }else{
            //没有值，则代表未登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在当前线程执行完毕后清空掉保存的用户信息
        LoginUserContext.removeLoginUser();
    }
}
